#define _CRT_SECURE_NO_WARNINGS 1
#include "List.h"

ListNode* ListInit()
{
	ListNode* Guard=(ListNode*)malloc(sizeof(ListNode));
	if (Guard == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	Guard->next = Guard;
	Guard->prev = Guard;
	return Guard;
}

ListNode* BuyListNode(LTDataType x)
{
	ListNode* newnode = (ListNode*)malloc(sizeof(ListNode));
	if (newnode == NULL)
	{
		perror("malloc fail");
		exit(-1);
	}
	newnode->data = x;
	newnode->next = NULL;
	newnode->prev = NULL;
	return newnode;
}

void ListPushBack(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	ListNode* tail = phead->prev;

	tail->next = newnode;
	newnode->prev = tail;
	newnode->next = phead;
	phead->prev = newnode;
}

void ListPushFront(ListNode* phead, LTDataType x)
{
	assert(phead);
	ListNode* newnode = BuyListNode(x);
	ListNode* cur = phead->next;
	phead->next = newnode;
	newnode->prev = phead;
	newnode->next = cur;
	cur->prev= newnode;
}

void ListNodePopBack(ListNode* phead)
{
	assert(phead);
	assert(!ListNodeEmpty(phead));
	ListNode* tail = phead->prev;
	ListNode* cur = tail->prev;
	cur->next = phead;
	phead -> prev = cur;
	free(tail);
	tail = NULL;
}

void ListNodePopFront(ListNode* phead)
{
	assert(phead);
	assert(!ListNodeEmpty(phead));
	ListNode* cur = phead->next;
	ListNode* pe = cur->next;
	phead->next = pe;
	pe->prev = phead;
	free(cur);
	cur = NULL;
}

bool ListNodeEmpty(ListNode* phead)
{
	assert(phead);
	return phead->next==phead;
}

size_t ListNodeSize(ListNode* phead)
{
	size_t n = 0;
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		++n;
		cur = cur->next;
	}
	return n;
}

ListNode* ListNodeFInd(ListNode* phead, LTDataType x)
{
	ListNode* cur = phead->next;
	while (cur != phead)
	{
		if (cur->data == x)
			return cur;
		cur = cur->next;
	}
	return NULL;
}

void ListNodeInsert(ListNode* pos, LTDataType x)
{
	assert(pos);
	ListNode* prev = pos->prev;
	ListNode* newnode = BuyListNode(x);
	prev->next = newnode;
	newnode->prev = prev;
	newnode->next = pos;
	pos->prev = newnode;
}

void ListNodeErase(ListNode* pos)
{
	assert(pos);

	ListNode* prev = pos->prev;
	ListNode* next = pos->next;
	prev->next = next;
	next->prev = prev;
	free(pos);
	pos = NULL;
}

void ListNodeDestory(ListNode* phead)
{
	assert(phead);

	ListNode* cur = phead->next;
	while (cur != phead)
	{
		ListNode* next = cur->next;
		free(cur);
		cur = next;
	}
	free(phead);
	phead = NULL;
}